import React, { Component, Suspense } from 'react';
import { connect } from 'dva';
import GridContent from '@/components/PageHeaderWrapper/GridContent';
import PageLoading from '@/components/PageLoading';
import { Button, message, Form, Col, Select  } from 'antd';
import styles from '@/pages/Account/Settings/BaseView.less';
import savebuttom from '@/assets/account/robotSetup/savebuttom.png';

const Item = React.lazy(() => import('./item'));
const { Option } = Select;

@connect(({ collectSlot, loading }) => ({
  collectSlot,
  loading: loading.effects['collectSlot/fetchSlot'],
}))
class Set extends Component {
  constructor(props) {
    super(props);
    this.state = {
      dialogSlots: [],
      nodeId: props.nodeId,
      stage: props.stage,
      dialogId: props.dialogId,// 多轮对话id
      setting:{
        mapping:[],
        uniqueSlot:"",
        apiId:"",
        resultTitle:{
          multiResultTitle:"",
          singleResultTitle:""
        },
        noResultTitle:"",
        noResultAction:"",
        resultTemplate:"",
        field:"",
        filter:"",
        noResFilter:""
      },
      apiList:[],
      fieldList:[],
      apiObj:{
        requestFields:[],
        responseFields:[]
      }
    }
  }

  componentDidMount() {
    this.fetchSlot();
    this.loadActionApis();
  }

  fetchSlot=()=>{
    const { dispatch } = this.props;
    const { dialogId,nodeId,stage} = this.state;
    let {setting,dialogSlots} = this.state;
    dispatch({
      type: 'collectSlot/fetchSlot',
      payload: {
        dialogId,nodeId,
        stage
      },
      callback:(res)=>{
        console.log('查询筛选模块-设置数据',res);
        if(res.code === 0 && res.code != undefined){
            return false;
        }
        setting = res.dialogStage.setting ;
        dialogSlots = res.dialogSlots;
        if(!setting){
          setting={
            mapping:[],
            uniqueSlot:"",
            apiId:"",
            resultTitle:{
              multiResultTitle:"",
              singleResultTitle:""
            },
            noResultTitle:"",
            noResultAction:"",
            resultTemplate:"",
            field:"",
            filter:"",
            noResFilter:""
          }
        }
        if(!dialogSlots){
            dialogSlots=[]
        }
        if(setting.apiId){
          this.getApiInfo(setting.apiId,true)
        }
        this.setState({
          dialogSlots,
          setting
        })
      }
    });
  };


  getAllDict=()=>{
    const { dispatch } = this.props;
    const { dialogId} = this.state;
    dispatch({
      type: 'collectSlot/getAllDict',
      payload: {
        dialogId,
      },
      callback:(res)=>{
        if(res.code === 0 && res.code != undefined){
            return false;
        }
       this.setState({
           dicts:res
       })
      }
    });
  };


  loadActionApis = () => {
    const { dispatch } = this.props;
    dispatch({
      type: 'dialogCommon/loadActionApis',
      payload: {
        page: 0,
        limit: 99999,
      },
      callback: (res) => {
        this.setState({
          apiList: res == null ? [] : res,
        });
      }
    });
  };

  getApiInfo= (id,isFirst)=>{
    const { dispatch } = this.props;
    dispatch({
      type: 'dialogCommon/loadActionApi',
      payload: {
        apiId:id
      },
      callback:(res)=>{
        if(res.code === 0&& res.code != undefined){
          return false;
        }
        if(isFirst){
          this.setState({
            fieldList:res.responseFields.concat(res.requestFields),
            apiObj:res
          })
        }else{
          this.setState({
            fieldList:res.responseFields,
            apiObj:res
          })
        }
      }
    });
  };

  fixData=(arr)=>{
    let {setting} = this.state;
    setting = arr;
    this.setState({
      setting
    })
  };

  fixFieldList = (type)=>{
    let {apiObj,fieldList} = this.state;
    if(type === 'request'){
      fieldList = apiObj.requestFields;
    }else{
      fieldList = apiObj.responseFields;
    }
    fieldList = apiObj[type+'Fields'];
    this.setState({
      fieldList
    })
  };

  saveSlotCheck=()=>{
    const { dispatch,closeDrawer } = this.props;
    const { dialogId,nodeId,setting} = this.state;
    if(this.Setting.getEditContent() === ''){
      return message.error('展示模版不能为空')
    }
    setting.resultTemplate = this.Setting.getEditContent();
    dispatch({
      type: 'collectSlot/saveSlot',
      payload: {
        field:'setting',
        _id:`${dialogId}-${nodeId}`,
        setting
      },
      callback:(res)=>{
        if(res.code && res.code !== undefined){
          return false;
        }
        message.info('保存成功');
        closeDrawer();
      }
    });
  };

  render() {
    const {dialogSlots,setting,apiList,apiObj} = this.state;
    return (
      <GridContent>
        <Suspense fallback={<PageLoading />}>
          <Col>
            <Item
              data={setting}
              apiData={apiList}
              fields={apiObj}
              dialogs={dialogSlots}
              updata={(res)=>this.fixData(res)}
              getApiDetail={(id)=>this.getApiInfo(id)}
              updataField={(type)=>this.fixFieldList(type)}
              wrappedComponentRef={e => this.Setting = e}
            />
            {/*<Button type="primary" htmlType='button' onClick={()=>this.saveSlotCheck()} style={{marginTop:20}}>保存</Button>*/}
            <div className={styles.flexcen}>
              <img onClick={this.saveSlotCheck} src={savebuttom} />
            </div>
          </Col>
        </Suspense>
      </GridContent>
    );
  }
}

export default connect (({ user }) => ({
  currentUser: user.currentUser
}))(Form.create()(Set));
